package cn.iocoder.yudao.module.erp.controller.admin.stocksmove;

import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.DEPT_EXISTS;

import cn.iocoder.yudao.module.erp.controller.admin.stocksmove.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.stocksmove.StocksMoveDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stocksmoveitem.StocksMoveItemDO;
import cn.iocoder.yudao.module.erp.service.stocksmove.StocksMoveService;

@Tag(name = "管理后台 - ERP 库存调拨单")
@RestController
@RequestMapping("/erp/stocks-move")
@Validated
public class StocksMoveController {

    @Resource
    private StocksMoveService stocksMoveService;
    @Resource
    private DeptMapper deptMapper;

    @PostMapping("/create-stocks-on-move-item")
    @Operation(summary = "创建ERP 库存调拨单")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:create')")
    public CommonResult<Boolean> createStocksOnMoveItem(@Valid @RequestBody StocksMoveSaveReqVO createReqVO) {
        stocksMoveService.createStocksOnMoveItem(createReqVO);
        return success(true);
    }
    @PostMapping("/create")
    @Operation(summary = "创建ERP 库存调拨单")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:create')")
    public CommonResult<Long> createStocksMove(@Valid @RequestBody StocksMoveSaveReqVO createReqVO) {
        return success(stocksMoveService.createStocksMove(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP 库存调拨单")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:update')")
    public CommonResult<Boolean> updateStocksMove(@Valid @RequestBody StocksMoveSaveReqVO updateReqVO) {
        stocksMoveService.updateStocksMove(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除ERP 库存调拨单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:delete')")
    public CommonResult<Boolean> deleteStocksMove(@RequestParam("id") Long id) {
        stocksMoveService.deleteStocksMove(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP 库存调拨单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:query')")
    public CommonResult<StocksMoveRespVO> getStocksMove(@RequestParam("id") Long id) {
        StocksMoveDO stocksMove = stocksMoveService.getStocksMove(id);
        StocksMoveRespVO moveRespVO = BeanUtils.toBean(stocksMove, StocksMoveRespVO.class);
//        给moveRespVO设置入库名称
        DeptDO deptDO = deptMapper.selectById(stocksMove.getToWarehouseId());
        // 非空检验
        if (deptDO == null) {
            throw exception(DEPT_EXISTS);
        }
        moveRespVO.setToWarehouseName(deptDO.getName());
        return success(moveRespVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP 库存调拨单分页")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:query')")
    public CommonResult<PageResult<StocksMoveRespVO>> getStocksMovePage(@Valid StocksMovePageReqVO pageReqVO) {
        PageResult<StocksMoveDO> pageResult = stocksMoveService.getStocksMovePage(pageReqVO);
        PageResult<StocksMoveRespVO> respVOPageResult = BeanUtils.toBean(pageResult, StocksMoveRespVO.class);
//        设置入库名称
        List<Long> collect = respVOPageResult.getList().stream().map(StocksMoveRespVO::getToWarehouseId).collect(Collectors.toList());
        List<DeptDO> deptDOList = deptMapper.selectBatchIds(collect);
        Map<Long, String> stringMap = deptDOList.stream().collect(Collectors.toMap(DeptDO::getId, DeptDO::getName));
        respVOPageResult.getList().forEach(stocksMoveRespVO -> {
            stocksMoveRespVO.setToWarehouseName(stringMap.get(stocksMoveRespVO.getToWarehouseId()));
        });
        return success(respVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP 库存调拨单 Excel")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportStocksMoveExcel(@Valid StocksMovePageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StocksMoveDO> list = stocksMoveService.getStocksMovePage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "ERP 库存调拨单.xls", "数据", StocksMoveRespVO.class,
                BeanUtils.toBean(list, StocksMoveRespVO.class));
    }

    // ==================== 子表（ERP 库存调拨项） ====================

    @GetMapping("/stocks-move-item/list-by-move-id")
    @Operation(summary = "获得ERP 库存调拨项列表")
    @Parameter(name = "moveId", description = "调拨编号")
    @PreAuthorize("@ss.hasPermission('erp:stocks-move:query')")
    public CommonResult<List<StocksMoveItemDO>> getStocksMoveItemListByMoveId(@RequestParam("moveId") Long moveId) {
        return success(stocksMoveService.getStocksMoveItemListByMoveId(moveId));
    }

}